<?php
//by willson 105328468@qq.com 2014/10/11
class passport extends core {
	public $member_mod;
	public function __construct() {
		parent::__construct();
		$this->member_mod = m('member');
	}

	//登录
	public function login() {
		//$this->clearsession();
		if (isset($_SESSION['member'])) unset($_SESSION['member']);
		if (isset($this->member) && $this->member_id>0) $this->member_id = 0;
		$mobile = $this->request->post('mobile');
		$password = $this->request->post('password');
		$udid = $this->request->post('udid');
		//微信的信息
		$nick_name = $this->request->post('nick_name');
		$avatar = $this->request->post('avatar');
		$sex = $this->request->post('sex');
		$province = $this->request->post('province');
		$city = $this->request->post('city');
		//openid不为空，表示从微信访问过来，直接使用openid登录
		$member = "";
		$openid = trim($this->request->get('openid'));
		if ($this->is_weixin() && $this->weixin_authed() && $openid) { //增加判断$_GET['openid']为了区分是否主动登录
			$_SESSION['openid'] = $openid;
			$member = $this->member_mod->find("openid='{$openid}'", 1);
			//var_dump($member);
			//exit;
		} else {
			if ($mobile == '') error('手机号码不能为空');
			if ($password == '') error('密码不能为空');
			$member = $this->member_mod->find("mobile='{$mobile}'", 1);
			if (!$member) {
				error('账号不存在');
			}
			$crypt_password = crypt_password($password, $member->salt);
			if ($crypt_password != $member->password) { //登录不成功
				error("账号或密码错误", -2);
			}
		}
		if ($member) {
			if ($member->status==1) {
				//推送强制下线通知
				if ($member->udid!='' && $member->udid!=$udid) {
					$this->notify->send($member->udid, "账号已在其他设备登录", "", "", array("action"=>"login", "state"=>-100), "ios");
				}
				
				$data = array();
				if ($udid!='') {
					//20150708 by ajsong 清除之前登录过的有相同udid的账号的udid
					$this->member_mod->update("udid='{$udid}'", "udid=''");
				}
				$data['udid'] = $udid;
				
				//环信登录需要原始密码
				if ($password) $data['origin_password'] = $password;
				$data['last_time'] = time();
				$data['last_ip'] = ip();
				$data['logins'] = array("logins", "+1");
				$this->member_mod->update($member->id, $data);
				$this->_after_passport($member, true, false);
			} else {
				error("账号已经被冻结", -1);
			}
		} else if ($this->is_weixin() && $this->weixin_authed() && $openid) {
			$url = (isset($_SESSION['weixin_url']) && trim($_SESSION['weixin_url'])) ? trim($_SESSION['weixin_url']) : 'wap.php';
			header("location:{$url}");
		}
	}
	
	//注册
	public function register() {
		//$this->clearsession();
		if (isset($_SESSION['member'])) unset($_SESSION['member']);
		if (isset($this->member) && $this->member_id>0) $this->member_id = 0;
		$mobile = $this->request->post('mobile');
		$password = $this->request->post('password');
		$code = $this->request->post('code');
		$invite_code = $this->request->post('invite_code');
		$udid = $this->request->post('udid');
		$session_code = $this->request->session('verify_code');
		$session_mobile = $this->request->session('verify_mobile');
		$salt = generate_salt();
		$crypt_password = crypt_password($password, $salt);
		//print_r($_SESSION);
		//微信的信息
		$nick_name = $this->request->post('nick_name');
		$avatar = $this->request->post('avatar');
		$sex = $this->request->post('sex');
		$province = $this->request->post('province');
		$city = $this->request->post('city');
		//openid不为空，表示从微信访问过来，直接使用openid登录
		$member = "";
		$openid = trim($this->request->post('openid'));
		if (!$openid) $openid = (isset($_SESSION['openid']) && trim($_SESSION['openid'])) ? trim($_SESSION['openid']) : '';
		//注册信息
		$data = array();
		$data['name'] = $mobile;
		$data['mobile'] = $mobile;
		$data['reg_time'] = time();
		$data['reg_ip'] = $this->ip;
		$data['last_time'] = time();
		$data['last_ip'] = $this->ip;
		$data['logins'] = 1;
		$data['status'] = 1;
		$data['udid'] = $udid;
		$data['invite_code'] = $invite_code;
		$data['origin_password'] = $password;
		$data['salt'] = $salt;
		$data['password'] = $crypt_password;
		$data['openid'] = $openid;
		$data['nick_name'] = $nick_name;
		$data['sex'] = $sex;
		$data['province'] = $province;
		$data['city'] = $city;
		$data['avatar'] = $avatar;

		if ($mobile == '') error('手机号码不能为空');
		if ($code == '') error('手机验证码不能为空');
		if ($password == '') error('密码不能为空');
		if ($code != $session_code) error('手机验证码不正确');
		if ($mobile != $session_mobile) error('手机号码不正确');
		//注册
		if ($this->member_mod->exists("mobile='{$mobile}'")) {
			error("手机号码已经被注册");
		}
		
		$reseller_id = (isset($_SESSION['reseller_id']) && trim($_SESSION['reseller_id'])) ? trim($_SESSION['reseller_id']) : '';
		if ($invite_code) {
			$invitor = $this->member_mod->find("invite_code='{$invite_code}'", 1);
			if (!$invitor) {
				error("邀请码无效");
			}
			//邀请人id
			$data['parent_id'] = $invitor->id;
		} else if ($reseller_id) {
			$data['parent_id'] = $reseller_id;
		}
		if ($udid!='') {
			//20150708 by ajsong 清除之前登录过的有相同udid的账号的udid
			$this->member_mod->update("udid='{$udid}'", "udid=''");
		}
		//20160222 by willson 绑定微信openid
		//20160322 by ajsong 增加更新头像,与微信同步
		if ($openid && isset($_SESSION['weixin'])) {
			$data['nick_name'] = $_SESSION['weixin']->nickname;
			$data['sex'] = $_SESSION['weixin']->sex;
			$data['province'] = $_SESSION['weixin']->province;
			$data['city'] = $_SESSION['weixin']->city;
			$data['avatar'] = $_SESSION['weixin']->avatar;
		}
		//写入
		//微信登录,为兼容日后主动登录,所以把name记录为手机号码
		//print_r($data);
		//exit;
		$this->member_mod->insert($data);
		//exit;
		$member_id = $this->db->insert_id;
        //生成新用户的邀请码
        $new_invite_code = 0;
        do {
            //by willson 2016/3/7 随机数+id
            $new_invite_code = rand(10000,50000) + $member_id;
            $sql = "SELECT * FROM jf_member WHERE invite_code='{$new_invite_code}'";
        } while ($this->db->get_row($sql));
        $this->member_mod->update($member_id, "invite_code='{$new_invite_code}'");
        //
		$member = $this->member_mod->find($member_id);
		if (!$member) {
			error("注册失败");
		}
		$this->_after_passport($member, false, true);
	}

	//主动调用微信登录
	public function wx_login(){
		//20160322 by ajsong 先判断是否已经进行认证(因为有可能是认证返回到这个接口)
		if ($this->is_weixin() && $this->weixin_authed()) {
			header("Location:api.php?app=passport&act=login&openid=".$_SESSION['openid']); //需要使用header跳转,为了指定当前不是主动登录
		} else {
			if ($this->is_weixin()) {
				$url = (isset($_SESSION['weixin_url']) && trim($_SESSION['weixin_url'])) ? trim($_SESSION['weixin_url']) : 'wap.php';
				header("location:{$url}"); //因为非微信端不能使用认证登录
			} else {
				$this->weixin_login(); //进行认证跳转
			}
		}
		exit;
	}

	//检查APP本地sign与数据库的sign是否一样，不一样即登录失效
	//20150715 by ajsong 增加获取当前收入(自动判断是否已开店)
	public function check_sign() {
		$id = intval($this->request->get('id'));
		$sign = trim($this->request->get('sign'));
		if ($id && $sign) {
			if ($this->member_mod->count("id='{$id}' AND sign='{$sign}'")==1) {
				$flag = 1;
				success($flag);
			} else {
				error("该账号已在其他设备登录", -9);
			}
		} else {
			//error("请登录", -100);
			error("请登录");
		}
	}

	//检查手机是否被注册，以及发送注册验证码
	public function send_sms() {
		$mobile = trim($this->request->post('mobile'));
		if ($mobile) {
			$code = rand(1000,9999);
			$content = array("number"=>$code);
			send_sms($mobile, $content);
			$_SESSION['login_sms_code'] = $code;
			$_SESSION['login_sms_mobile'] = $mobile;
			success(array("code"=>$code, "mobile"=>$mobile));
		} else {
			error("请输入合法手机号码");
		}
	}

	//检查手机是否被注册，以及发送注册验证码
	public function check_mobile() {
		$url = (isset($_REQUEST['url']) && trim($_REQUEST['url'])) ? trim($_REQUEST['url']) : '';
		$mobile = isset($_POST['mobile']) && $_POST['mobile'] ? $_POST['mobile'] : '';
		if ($mobile) {
			if (!$this->member_mod->exists("mobile='{$mobile}'")) {
				$code = rand(1000,9999);
				//$content = '您的手机注册验证码是'.$code.'。';
				$content = "欢迎新会员注册，注册验证码：{$code}";
				send_sms($mobile, $content);
				$_SESSION['verify_code'] = $code;
				$_SESSION['verify_mobile'] = $mobile;

				success(array("code"=>$code, "mobile"=>$mobile));
			} else {
				error('手机号码已经被注册');
			}
		} else {
			error("请输入合法手机号码");
		}
	}

	//处理登录或注册后的操作
	private function _after_passport($member, $is_login=false, $is_register=false, $avatar='') {
		if (!$member && !is_object($member)) error('member is not an object');
		
		//生成签名
		if ($this->is_weixin() && $is_login) {
			$sign = $member->sign;
		} else {
			//20160322 by ajsong 不理是否微信登录都更新一下sign会好点
			$sign = md5(md5(rand(100000,999999)).time());
			$member->sign = $sign;
			$this->member_mod->update($member->id, "sign='{$sign}'");
		}

		//设置登录信息
		$this->sign = $sign;
		$this->_check_login();

		//$member->avatar = $this->get_avatar();
		if ($member->avatar) {
			$member->avatar = add_domain($member->avatar);
		} else {
			$member->avatar = add_domain("/images/avatar.jpg");
		}
		//生成缩略图
		//$member->avatar = $member->avatar."!logo";
		$member->format_reg_time = date('Y-m-d', $member->reg_time);
		$member = add_domain_deep($member, array("avatar"));
		if ($is_register) {
			
		}
		
		//登录与注册都需要记录openid
		if (isset($_SESSION['openid'])) {
			$this->member_mod->update($member->id, "openid='".$_SESSION['openid']."'");
		}
		
		//更新在线
		$this->member_mod->update($member->id, "session_id='".session_id()."'");
		
		//更新购物车
		/*$sql = "UPDATE jf_cart SET member_id='{$member->id}' WHERE session_id='".session_id()."'";
		$this->db->query($sql);*/
		
		//微信端跳转回之前查看的页面
		if ($this->is_weixin() && $is_login) {
			$url = (isset($_SESSION['weixin_url']) && trim($_SESSION['weixin_url'])) ? trim($_SESSION['weixin_url']) : 'wap.php';
			header("location:{$url}");
		}
		
		success($member);
	}

	//忘记密码 - 发送手机号码和验证短信
	public function forget_send_sms() {
		$mobile = isset($_POST['mobile']) && $_POST['mobile'] ? $_POST['mobile'] : '';
		if ($mobile) {
			$sql = "SELECT COUNT(*) FROM jf_member WHERE mobile='{$mobile}'";
			$num = intval($this->db->get_var($sql));
			if ($num==1) {
				$code = rand(1000,9999);
				//$content = '您的手机验证码是'.$code.'。';
				//send_sms($mobile, $content);
				send_sms($mobile, $code);
				$_SESSION['forget_sms_code'] = $code;
				$_SESSION['forget_sms_mobile'] = $mobile;
				success(array("code"=>$code, "mobile"=>$mobile));
			} elseif ($num>1) {
				error('该手机号码被重复注册，无法找回密码，请联系管理员');
			} else {
				error('该手机号码没在系统注册');
			}
		} else {
			erorr("请输入合法手机号码");
		}
	}

	//忘记密码
	public function forget() {
		require_once(FRAMEWORK_PATH . "/third/emchat/Easemob.class.php");
		$mobile = isset($_POST['mobile']) && $_POST['mobile'] ? $_POST['mobile'] : '';
		$code = isset($_POST['code']) && $_POST['code'] ? $_POST['code'] : '';
		$password = isset($_POST['password']) && $_POST['password'] ? $_POST['password'] : '';
		$newpassword = $password;
		if ($mobile && $code && $password) {
			if (isset($_SESSION['forget_sms_code']) && $code == $_SESSION['forget_sms_code']) {
				$sql = "SELECT id, name, mobile FROM jf_member WHERE mobile='{$mobile}'";
				$member = $this->db->get_row($sql);
				if ($member) {
					$salt = generate_salt();
					$crypt_password = crypt_password($password, $salt);
					$sql = "UPDATE jf_member SET password='{$crypt_password}', origin_password='{$password}', salt='{$salt}' WHERE id='{$member->id}'";
					$this->db->query($sql);
					// $options = array(
					// 	"client_id" => $this->easemob_client_id,
					// 	"client_secret" => $this->easemob_client_secret,
					// 	"org_name" => $this->easemob_org_name,
					// 	"app_name" => $this->easemob_app_name,
					// );
					// $easmob = new Easemob($options);
					// $options = array(
					// 	"username"=>$member->id,
					// 	"newpassword"=>$newpassword
					// );
					// $easmob->editPassword($options);
					success($member->name, "修改密码成功，登录账号{$member->mobile}");
				} else {
					error("无此会员");
				}
			} else {
				error("验证码不正确");
			}
		} else {
			erorr("请提交电话、验证码和密码参数");
		}
	}

	//退出
	public function logout(){
		$this->clearsession();
		success("ok");
	}

	//清除session
	private function clearsession() {
		session_unset();
		if (isset($_SESSION['member'])) unset($_SESSION['member']);
		if (isset($this->member) && $this->member_id>0) $this->member_id = 0;
	}
 }
